<?php

/*
 * This file is part of ibrand/EC-Open-Server.
 *
 * (c) iBrand <https://www.ibrand.cc>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace iBrand\EC\Open\Server\Http\Controllers;

use App\Libs\Util;
use EasyWeChat;
use iBrand\Component\Payment\Services\PaymentService;
use Illuminate\Support\Facades\DB;

class WechatPayNotifyController extends Controller
{
    private $payment;

    public function __construct(PaymentService $paymentService)
    {
        $this->payment = $paymentService;
    }


    public function notify(){
        try{
            $xml = file_get_contents("php://input");
            if(!$xml)
            {
                exit;
            }

            $data = Util::xmlToArray($xml);
            savelog('wx_log', ($xml));
            if($data && $data['result_code']=='SUCCESS') {
                $where = array(
                    'order_no'=>$data['attach'],
                );

                $orderinfo = DB::table('ibrand_order')->where($where)->first();
                if (!$orderinfo) {
                    fun_respon(0, '订单不存在');
                }
                if ($orderinfo->status == 2 ) {
                    savelog('wx_fault', '订单已经支付过'.$orderinfo->order_no.json_encode($data));
                    echo 'SUCCESS';exit;
                }
                DB::beginTransaction();
                if($orderinfo->type==1){
                    $arrs = explode('_',$orderinfo->channel);
                    $at_id = $arrs[3];
                    $ac_id = $arrs[4];
                    $datas = ['user_id'=>$orderinfo->user_id,'activity_goods_id'=>$arrs[1],'sku'=>$arrs[2],'ac_id'=>$ac_id,'created_at'=>date("Y-m-d H:i:s",time())];
                    //添加信息
                    if($at_id==0){
                        $at_id = DB::table('activity_team')->insertGetId(['ac_id'=>$ac_id,'user_id'=>$orderinfo->user_id,'activity_goods_id'=>$arrs[1],'sku'=>$arrs[2],'created_at'=>date("Y-m-d H:i:s",time())]);
                        $datas['at_id'] = $at_id;
                        DB::table('activity_users')->insertGetId($datas);
                    }else{
                        $datas['at_id'] = $at_id;
                        //判断队伍人数是否已经满了
                        $activity = DB::table('activity')->where(['ac_id'=>$ac_id])->first();
                        //查询队伍已存在的人数
                        $activity_users = DB::table('activity_users')->where(['at_id'=>$at_id,'activity_goods_id'=>$arrs[1],'sku'=>$arrs[2]])->get();
                        $nums = count($activity_users);
                        if($nums+1 >= $activity->activity_num){
                            //$datas['is_succeed']=1;
                            DB::table('activity_team')->where(['at_id'=>$at_id])->update(['is_succeed'=>1]);
                        }
                        DB::table('activity_users')->insertGetId($datas);
                    }
                    //增加数量
                    DB::table('activity_goods')->where(['sku'=>$arrs[2]])->increment('join_num');
                    $str = $orderinfo->user_id.'_'.$arrs[1].'_'.$arrs[2].'_'.$at_id.'_'.$ac_id;
                    //推送模板消息
                    //查询用户
                    $user_info = DB::table('ibrand_user')->where(['id'=>$orderinfo->user_id])->first(['openid']);
                    $template_id = 'XdjS71nMe7Uc_ToV8jmQZgtz70JnEU8vhts7LrSUwx4';
                    $datas = array(
                        'keyword1'=>array('value'=>'暴抱团','color'=>'#7167ce'),
                        'keyword2'=>array('value'=>'您参与的暴抱团已经拼团成功啦！','color'=>'#7167ce'),
                    );
                    sendTemplate($user_info->openid,$datas,$template_id);

                }
                $arr = array(
                    'status'=>2,
                    'pay_status'=>1,
                    'pay_json'=>json_encode($data),
                    'trade_no'=>$data['transaction_id'],
                    'pay_time'=>date('Y-m-d H:i:s', time()),
                    'is_valid'=>1
                );
                if(isset($str)) $arr['channel'] = $str;
                DB::table('ibrand_order')->where($where)->update($arr);
                $user = DB::table('ibrand_user')->where(['id'=>$orderinfo->user_id])->first();
                $openid = $user->openid;
                //加积分
                $member_info = get_member($openid);
                if($member_info){
                    $before_bonus = $member_info->bonus;
                    $change_bonus = ceil($orderinfo->total/100);
                    $after_bonus = $before_bonus+$change_bonus;
                    $status = 1;
                    $type = 1;
                    //调用微信的接口加积分
                    $record_bonus = sprintf("消费%s元，获取%u积分", $change_bonus, $change_bonus);
                    $result = Util::updateMember($member_info->code,$record_bonus,$change_bonus);
                    if($result['errcode']==0){
                        add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,1,'');
                    }else{
                        savelog('wx_bonus', '订单已经支付过'.$orderinfo->order_no	.'错误：'.$result['errmsg']);
                    }
                }
                DB::commit();
                savelog('wx_success', json_encode($data));
                echo 'SUCCESS';exit;
            } else {
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[error]]></return_msg></xml>";
            }
        }catch (\Exception $exception) {
            DB::rollBack();
            var_dump($exception->getMessage() . $exception->getLine());
            \Log::info($exception->getMessage() . $exception->getTraceAsString());
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[error]]></return_msg></xml>";
        }
    }
}
